import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { ToastController, Events } from 'ionic-angular';
import { AppGlobal } from './appGlobal';
/*
  Generated class for the HttpService provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpService {

  constructor(public http: Http,
    public events: Events,
    public toastCtrl: ToastController) {
    //console.log('Hello HttpService Provider');
  }


  public get(url: string, paramObj: any) {
    return this.http.get(url + this.toQueryString(paramObj))
      .toPromise()
      .then(res => this.handleSuccess(res.json()))
      .catch(error => this.handleError(error));
  }

  public post(url: string, paramObj?: any) {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    if(true){
      // headers.append('Authorization', AppGlobal.getInstance().h_token);
    }
    return this.http.post(url, this.toBodyString(paramObj), new RequestOptions({ headers: headers }))
      .toPromise()
      .then(res => this.handleSuccess(res.json()))
      .catch(error => this.handleError(error));
  }

  public postBody(url: string, paramObj: any = {}) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Authorization', AppGlobal.getInstance().getToken());
    
    return this.http.post(url, paramObj, new RequestOptions({ headers: headers }))
      .toPromise()
      .then(res => this.handleSuccess(res.json()))
      .catch(error => this.handleError(error));
  }

  private handleSuccess(result) {

    // console.log(result);
    if (result && !result.code) {
      return  Promise.reject(result);
      // return result.data;
    }
    return result.data;

  }

  private handleError(error: Response | any) {
    let msg = '请求失败';
    console.log(error);
    if (error.status == 0) {
      msg = '请求地址错误或用户验证失败';
    }
    if (error.status == 400) {
      msg = '请求无效';
      console.log('请检查参数类型是否匹配');
    }
    if (error.status == 401) {
      msg = '用户验证失败';
      console.log('用户验证失败 401');
    }
    if (error.status == 404) {
      msg = '请求资源不存在';
      console.error(msg + '，请检查路径是否正确');
    }
    if(error.code == 0){
      msg = error.msg;
    }
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 3000
    });
    toast.present();
    if(msg== "token校验失败" || error.status == 0 || error.status == 401){
      this.events.publish('LOGOUT');
    }
    // console.error(error,msg);
    return  Promise.reject(error.msg);
  }

  /**
   * @param obj　参数对象
   * @return {string}　参数字符串
   * @example
   *  声明: var obj= {'name':'小军',age:23};
   *  调用: toQueryString(obj);
   *  返回: "?name=%E5%B0%8F%E5%86%9B&age=23"
   */
  private toQueryString(obj) {
    let ret = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor == Array) {//数组
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        ret = ret.concat(queryValues);
      } else { //字符串
        ret.push(this.toQueryPair(key, values));
      }
    }
    return '?' + ret.join('&');
  }

  /**
   *
   * @param obj
   * @return {string}
   *  声明: var obj= {'name':'小军',age:23};
   *  调用: toQueryString(obj);
   *  返回: "name=%E5%B0%8F%E5%86%9B&age=23"
   */
  private toBodyString(obj) {
    let ret = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor == Array) {//数组
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        ret = ret.concat(queryValues);
      } else { //字符串
        ret.push(this.toQueryPair(key, values));
      }
    }
    return ret.join('&');
  }

  private toQueryPair(key, value) {
    if (typeof value == 'undefined') {
      return key;
    }
    return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  }

}
